import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


//Check in test

public class Menu {

	public JMenuBar setMenuBar() {
		/*JFrame frame = new JFrame("Nine Mens Morris");
	frame.setVisible(false);
	frame.setSize(500,500);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);*/
		Global.globalFrame.setResizable(false);
		final View viewSystem = new View();
		try {
			Main mainSystem = new Main();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		final JFrame frame = Global.globalFrame;


		JMenuBar menubar = new JMenuBar();
		//frame.setJMenuBar(menubar);

		JMenu file = new JMenu("File");
		menubar.add(file);
		

		JMenu help = new JMenu("Help");
		menubar.add(help);
		//add help item
		JMenuItem rules= new JMenuItem("Rules",KeyEvent.VK_T);
		rules.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK));
		rules.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				viewSystem.setHelp(true);
			}
		});
		
		help.add(rules);
		//add menu items
		JMenu newGame = new JMenu("New Game");
		file.add(newGame);

		JMenuItem PVPGame = new JMenuItem("Player Vs Player",KeyEvent.VK_T);
		PVPGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
		PVPGame.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				//Global.playerOneString = Global.playerOneName.getText();
				//Global.playerTwoString = Global.playerTwoName.getText();
				frame.getContentPane().removeAll();
				viewSystem.setLoadGame(false,Global.globalFrame);
				viewSystem.setGameMenu(false,Global.globalFrame);
				viewSystem.setPVPSetup(true,Global.globalFrame);
			}
		});
		

		newGame.add(PVPGame);

		JMenuItem PVCGame = new JMenuItem("Player Vs Computer",KeyEvent.VK_T);
		PVCGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));	
		PVCGame.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				frame.getContentPane().removeAll();
				viewSystem.setLoadGame(false,Global.globalFrame);
				viewSystem.setGameMenu(false,Global.globalFrame);
				viewSystem.setPVPSetup(false,Global.globalFrame);
				viewSystem.setPVCSetup(true,Global.globalFrame);
			}
		});

		newGame.add(PVCGame);

		JMenuItem loadGame = new JMenuItem("Load Game",KeyEvent.VK_T);
		loadGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
		loadGame.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				frame.getContentPane().removeAll();
				viewSystem.setPVPGameBoard(false,Global.globalFrame);
				viewSystem.setGameMenu(false,Global.globalFrame);
				viewSystem.setLoadGame(true,Global.globalFrame);

			}
		});	
		file.add(loadGame);

		JMenuItem saveGame = new JMenuItem("Save Game",KeyEvent.VK_T);
		saveGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		saveGame.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				try {
					saveGame();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});	
		file.add(saveGame);
		
		JMenuItem undo = new JMenuItem("Undo",KeyEvent.VK_T);
		undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
		undo.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				if(!Global.isPVCMode || Main.getControllerSystem().getPlayerTurn() == 1){
					try {
						undo();
					} catch (ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}


			}
		});	
		file.add(undo);

		file.addSeparator();


		JMenu viewLeaderboard = new JMenu("View Leaderboard");
		file.add(viewLeaderboard);

		JMenuItem PVPLeaderboard = new JMenuItem("Player Vs Player",KeyEvent.VK_T);
		PVPLeaderboard.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, ActionEvent.CTRL_MASK));		
		PVPLeaderboard.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				frame.getContentPane().removeAll();
				Global.setPanelVisibility(false);
				viewSystem.setPVPGameBoard(false,Global.globalFrame);
				viewSystem.setLoadGame(false,Global.globalFrame);
				viewSystem.setGameMenu(false,Global.globalFrame);
				viewSystem.setLeaderboard(true, Global.globalFrame);

			}
		});	
		viewLeaderboard.add(PVPLeaderboard);
		JMenuItem PVCLeaderboard = new JMenuItem("Player Vs Computer",KeyEvent.VK_T);
		PVCLeaderboard.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, ActionEvent.ALT_MASK));		
		PVCLeaderboard.addActionListener(new ActionListener(){	
			public void actionPerformed(ActionEvent e)
			{
				frame.getContentPane().removeAll();
				Global.setPanelVisibility(false);
				viewSystem.setPVPGameBoard(false,Global.globalFrame);
				viewSystem.setLoadGame(false,Global.globalFrame);
				viewSystem.setGameMenu(false,Global.globalFrame);
				viewSystem.setLeaderboard(false, Global.globalFrame);
				viewSystem.setPVCLeaderboard(true, Global.globalFrame);
	
			}
		});			
		viewLeaderboard.add(PVCLeaderboard);

		JMenu clearLeaderboard = new JMenu("Clear Leaderboard");
		file.add(clearLeaderboard);

		JMenuItem PVPClearBoard = new JMenuItem("Player Vs Player",KeyEvent.VK_T);
		PVPClearBoard.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, ActionEvent.CTRL_MASK));
		PVPClearBoard.addActionListener(new ActionListener(){	
			public void actionPerformed(ActionEvent e)
			{
				ArrayList<User> users = Main.getModelSystem().getUsers();
				for(int i = 0; i < users.size(); i++){
					users.get(i).setGamesPlayed(0);
					users.get(i).setWins(0);
					try {
						Main.getModelSystem().updateUserFile();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		
		clearLeaderboard.add(PVPClearBoard);
		JMenuItem PVCClearBoard = new JMenuItem("Player Vs Computer",KeyEvent.VK_T);
		PVCClearBoard.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, ActionEvent.ALT_MASK));
		PVCClearBoard.addActionListener(new ActionListener(){	
			public void actionPerformed(ActionEvent e)
			{
				ArrayList<User> users = Main.getModelSystem().getUsers();
				for(int i = 0; i < users.size(); i++){
					users.get(i).setComputerGamesPlayed(0);
					users.get(i).setComputerWins(0);
					try {
						Main.getModelSystem().updateUserFile();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		clearLeaderboard.add(PVCClearBoard);

		file.addSeparator();

		JCheckBoxMenuItem enableFly = new JCheckBoxMenuItem("Enable Flying");
		enableFly.setMnemonic(KeyEvent.VK_F);
		enableFly.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
		enableFly.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				if(Main.getControllerSystem().isFlyingOn()){
					try {
						Main.getControllerSystem().setFlyingOn(false);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				else{
					try {
						Main.getControllerSystem().setFlyingOn(true);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		file.add(enableFly);


		file.addSeparator();

		JMenuItem exit = new JMenuItem("Exit",KeyEvent.VK_T);
		exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
		file.add(exit);
		exit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				Main.timer.cancel();
				System.exit(0);
			}
		});	
		
		
		return menubar;
	}
	
	public void loadGame(String pathName) throws IOException, ClassNotFoundException{
		
		// Main.setModelSystem(new Model());		// Fetches most current data from files.
		
		File gameFile = new File(pathName);
		if(gameFile.exists())
		{
			FileInputStream fis = new FileInputStream(pathName);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Main.getModelSystem().setGame((Game) ois.readObject());
			Main.getControllerSystem().setFlyingOn(Main.getModelSystem().getGame().isFlyingEnabled());
			ois.close();
		}
		
		
	}
	
	
	/*
	 * This method simply saves the game to a .game file instead of just the .recovery file.  As of right now,
	 * I believe this method is complete and no interface changes need to be made here.
	 */
	public void saveGame() throws IOException{
		Locale locale = new Locale("US");
		Date today;
		String result;
		SimpleDateFormat formatter;
		formatter = new SimpleDateFormat("MM_dd_yy", locale);
		today = new Date();
		result = formatter.format(today);
		
		String fileName = Main.getModelSystem().getGame().getUsers()[0].getName() + "_" + 
				Main.getModelSystem().getGame().getUsers()[1].getName() + "_" + result + ".game";
		
		File file;
		file = new File(fileName);
		if(!file.exists())
		{
			file.createNewFile();
		}
		
		FileOutputStream fos = new FileOutputStream(fileName);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(Main.getModelSystem().getGame());
		
		if(!Main.getModelSystem().getGameNames().contains(fileName)){
			Main.getModelSystem().getGameNames().add(fileName);
			Main.getModelSystem().updateGameHistory();
		}
	}
	
	public void newGame(String user1Name, String user2Name) throws IOException{
		Main.setModelSystem(new Model());		// Fetches most current data from files.
		
		boolean isFlyingEnabled = false;	//
		
		User users[] = new User[2];
		
		// Search for the names in the most recent user file.
		for(int i = 0; i < Main.getModelSystem().getUserNames().size(); i++)
		{
			if(user1Name.equals(Main.getModelSystem().getUserNames().get(i)))
			{
				users[0] = Main.getModelSystem().getUsers().get(i);
			}
			if(user2Name.equals(Main.getModelSystem().getUserNames().get(i)))
			{
				users[1] = Main.getModelSystem().getUsers().get(i);
			}
		}
		
		
		// Check if they were found, otherwise create new users.
		if(users[0] == null)
		{
			users[0] = new User(user1Name);
			users[0].setPlayerAvatar(Global.playerOneAvatar);
			users[0].setPlayerToken(Global.token1Color);
			Main.getModelSystem().getUserNames().add(users[0].getName());
			Main.getModelSystem().getUsers().add(users[0]);
			Main.getModelSystem().updateUserFile();
		}
		if(users[1] == null)
		{
			users[1] = new User(user2Name);
			users[1].setPlayerAvatar(Global.playerTwoAvatar);
			users[1].setPlayerToken(Global.token2Color);
			Main.getModelSystem().getUserNames().add(users[1].getName());
			Main.getModelSystem().getUsers().add(users[1]);
			Main.getModelSystem().updateUserFile();
		}
			
		Main.getModelSystem().setGame(new Game(users, isFlyingEnabled));
	}
	
	public void undo() throws ClassNotFoundException, IOException{
		Locale locale = new Locale("US");
		Date today;
		String result;
		SimpleDateFormat formatter;
		formatter = new SimpleDateFormat("MM_dd_yy", locale);
		today = new Date();
		result = formatter.format(today);
		
		String fileName = Main.getModelSystem().getGame().getUsers()[0].getName() + "_" + 
				Main.getModelSystem().getGame().getUsers()[1].getName() + "_" + result + ".recovery";
		loadGame(fileName);
		/*if(!Global.isPVCMode){
			Main.getControllerSystem().switchTurn();
		}*/
		Main.getViewSystem().clearBoard(true);
	}
	
	public void enableFlying() throws IOException{
		Main.getModelSystem().getGame().setFlyingEnabled(true);
	}
	
	public void disableFlying() throws IOException{
		Main.getModelSystem().getGame().setFlyingEnabled(false);
	}
	
	/*
	 * @lbChoice p for PvP, and c for PvC.
	 */
	
	// I'm starting to think this should a be a separate window to avoid game interuptions.
	public void viewLB(char lbChoice){
		ArrayList<User> users = Main.getModelSystem().getUsers();	// All of the statistics can be taken from here.
	}
	
	// This will just be a text file, and I think we should open a separate window for the help page.
	public void help(){
		
	}


}